package cn.itsource.hrm.userdetails;


import cn.itsource.hrm.domain.LoginUser;
import cn.itsource.hrm.mapper.LoginUserMapper;
import cn.itsource.hrm.mapper.PermissionMapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import cn.itsource.hrm.domain.Permission;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 将数据库中的认证的用户名 密码 权限等数据进行查询处理
 * username 此方法将username 传入参数进来  通过username查询用户的信息
 * 将密码和权限封成userDetails进行返回，交给security
 * security中自动封装了  UserDetails 需返回
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private LoginUserMapper loginUserMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        List<LoginUser> userList = loginUserMapper.selectList(new EntityWrapper<LoginUser>().eq("username", username));
        if (userList == null || userList.size() < 1){ // 校验参数 是否为空  或者大小小于1
            throw new UsernameNotFoundException("账户名不存在!"); // 抛出异常
        }

        LoginUser loginUser = userList.get(0); // 获取集合中下标 0 的数据

        // 1、从数据库中查询权限
        List<Permission> permissions = permissionMapper.loadPermissionsByUserId(loginUser.getId());

        //2 将查询出的权限封装成Details成为SPringsecurity所需要权限数据
        List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission -> {
            return new SimpleGrantedAuthority(permission.getSn());
        }).collect(Collectors.toList());

        return new User(loginUser.getUsername(),loginUser.getPassword(),authorities);
    }
}
